<template>
  <view class="filter-wrap">
    <view class="town-wrap">
      <wd-picker
        :columns="townState.options"
        v-model="townState.value"
        value-key="orgCode"
        label-key="title"
        use-default-slot
        @confirm="getData"
      >
        <view class="town-text">{{ townText }}</view>
      </wd-picker>
    </view>
    <view>
      <DatePicker v-model:date="date" @confirm="confirm" />
    </view>
  </view>
  <view class="chart-wrap">
    <BarChart :axis-data="axisData" :data="barData" :height="barHeight" ref="chartRef" />
  </view>
</template>

<script setup>
import DatePicker from './DatePicker.vue'
import BarChart from './BarChart.vue'
import BiApi from '@/service/bi'
import HallApi from '@/service/hall'
import dayjs from 'dayjs'
import { LH_DEPART_CODE } from '@/configs/constant'

const townState = reactive({
  value: '',
  options: [],
})
const townText = computed(() => {
  return townState.options.find((v) => v.orgCode === townState.value)?.title || ''
})

const date = ref([])

const formatDate = ref([])

const getTownData = async () => {
  const params = {
    pid: LH_DEPART_CODE,
    primaryKey: 'orgCode',
  }
  const { result } = await HallApi.getDepartTree(params)
  if (result?.length > 0) {
    townState.value = result[0].orgCode
    townState.options = [...result]
  } else {
    townState.options = []
  }
  initDate()
}

const initDate = () => {
  const today = new Date().getTime()
  const thirtyDaysAgo = new Date().getTime() - 30 * 24 * 60 * 60 * 1000
  date.value = [new Date(thirtyDaysAgo), new Date(today)]

  formatDate.value = [
    dayjs(date.value[0]).format('YYYY-MM-DD'),
    dayjs(date.value[1]).format('YYYY-MM-DD'),
  ]
}

const confirm = () => {
  formatDate.value = [
    dayjs(date.value[0]).format('YYYY-MM-DD'),
    dayjs(date.value[1]).format('YYYY-MM-DD'),
  ]
  getData()
}

const axisData = ref([])
const barData = ref([])
const barHeight = ref(300)

const chartRef = ref()

const getData = async () => {
  barData.value = []
  axisData.value = []
  const ret = await BiApi.getHallReport({
    startDate: formatDate.value?.[0] || '',
    endDate: formatDate.value?.[1] || '',
    orgCode: townState.value,
  })

  if (ret?.result?.length > 0) {
    ret.result.forEach((item) => {
      barData.value.unshift(item.value)
      axisData.value.unshift(item.label)
    })
    barHeight.value = 30 * ret.result.length
  } else {
    barHeight.value = 300
  }
  chartRef.value.initData()
}

const initData = () => {
  getTownData()
}

defineExpose({
  initData,
  getTownData,
  getData,
})
</script>

<style lang="scss" scoped>
$active-color: #8597ff;

.town-text {
  display: flex;

  // flex: 1;
  align-items: center;
  justify-content: center;

  // width: 130px;
  min-width: 110px;
  max-width: 130px;
  font-size: $uni-font-size-base;
  line-height: 40px;
  color: $active-color;
  background: $uni-bg-color;
  border-radius: $uni-border-radius-lg;
}
</style>
